﻿using Microsoft.EntityFrameworkCore;
using MudBlazor.Services;
using Polly;
using Polly.Retry;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using Tool.Components;
using Tool.Data;
using Tool.Services;
using Volo.Abp;
using Volo.Abp.Data;
using Volo.Abp.Identity;
using Volo.Abp.Uow;

namespace Tool
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add MudBlazor services
            builder.Services.AddMudServices();

            // 注册 ABP 模块
            builder.Services.AddApplication<ToolModule>();


            builder.Services.AddDbContext<ToolDbContext>(options =>
    options.UseSqlite(builder.Configuration.GetConnectionString("Default")));

            // Add services to the container.
            builder.Services.AddRazorComponents(options =>
            {
                options.DetailedErrors = true; //development only
            }).AddInteractiveServerComponents(options =>
            {
                options.DetailedErrors = true; //development only
            });
            #region http client
            builder.Services.AddHttpClient("encrypt", client =>
            {
                client.BaseAddress = new Uri("http://192.168.236.14:8888/");
            });

            builder.Services.AddHttpClient("zwy", client =>
            {
                client.BaseAddress = new Uri("https://yunwei.beijing.gwhome:34443/");
                client.DefaultRequestVersion = new Version(2, 0);
                client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
                client.Timeout = TimeSpan.FromSeconds(10);
            }).ConfigurePrimaryHttpMessageHandler(() =>
            {
                //var certs = X509CertificateLoader.LoadPkcs12CollectionFromFile("./certs/李克善.p12", "wXsjm1VN");
                //var handler = new HttpClientHandler  //两种clienthandler都支持
                //{
                //    ClientCertificates = { X509CertificateLoader.LoadPkcs12FromFile("./certs/李克善.pfx", "wXsjm1VN") },
                //    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true, // 仅测试
                //    ClientCertificateOptions = ClientCertificateOption.Manual,
                //    SslProtocols = SslProtocols.Tls13,
                //    UseCookies = true,
                //    AllowAutoRedirect = false,
                //};

                var certs = X509CertificateLoader.LoadPkcs12CollectionFromFile("./certs/李克善.p12", "wXsjm1VN");
                var handler = new SocketsHttpHandler
                {
                    UseCookies = true,
                    AllowAutoRedirect = false,
                    // 设置客户端证书
                    SslOptions = new SslClientAuthenticationOptions
                    {
                        TargetHost = "yunwei.beijing.gwhome",
                        //ClientCertificates = new X509CertificateCollection { cert },
                        ClientCertificates = certs,
                        // 设置服务器证书验证回调（仅测试用）
                        RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true,
                        // 设置 SSL/TLS 协议版本
                        EnabledSslProtocols = SslProtocols.Tls13,
                        // 设置客户端认证选项
                        CertificateRevocationCheckMode = X509RevocationMode.NoCheck,
                    }
                };

                return handler;

            });
            builder.Services.AddHttpClient("sx", client =>
            {
                client.BaseAddress = new Uri("https://yunwei.sxzwcloud.gwhome:34443/");
                client.DefaultRequestVersion = new Version(2, 0);
                client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
                client.Timeout = TimeSpan.FromSeconds(10);
            }).ConfigurePrimaryHttpMessageHandler(() =>
            {
                var certs = X509CertificateLoader.LoadPkcs12CollectionFromFile("./certs/李克善.p12", "wXsjm1VN");
                var handler = new SocketsHttpHandler
                {
                    UseCookies = true,
                    AllowAutoRedirect = false,
                    // 设置客户端证书
                    SslOptions = new SslClientAuthenticationOptions
                    {
                        TargetHost = "yunwei.sxzwcloud.gwhome",
                        //ClientCertificates = new X509CertificateCollection { cert },
                        ClientCertificates = certs,
                        // 设置服务器证书验证回调（仅测试用）
                        RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true,
                        // 设置 SSL/TLS 协议版本
                        EnabledSslProtocols = SslProtocols.Tls13,
                        // 设置客户端认证选项
                        CertificateRevocationCheckMode = X509RevocationMode.NoCheck,
                    }
                };

                return handler;

            });
            builder.Services.AddHttpClient("sh", client =>
            {
                client.BaseAddress = new Uri("https://yunwei.shanghai.gwhome:34443/");
                client.DefaultRequestVersion = new Version(2, 0);
                client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
                client.Timeout = TimeSpan.FromSeconds(10);
            }).ConfigurePrimaryHttpMessageHandler(() =>
            {
                var certs = X509CertificateLoader.LoadPkcs12CollectionFromFile("./certs/李克善.p12", "wXsjm1VN");
                var handler = new SocketsHttpHandler
                {
                    UseCookies = true,
                    AllowAutoRedirect = false,
                    // 设置客户端证书
                    SslOptions = new SslClientAuthenticationOptions
                    {
                        TargetHost = "yunwei.shanghai.gwhome",
                        //ClientCertificates = new X509CertificateCollection { cert },
                        ClientCertificates = certs,
                        // 设置服务器证书验证回调（仅测试用）
                        RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true,
                        // 设置 SSL/TLS 协议版本
                        EnabledSslProtocols = SslProtocols.Tls13,
                        // 设置客户端认证选项
                        CertificateRevocationCheckMode = X509RevocationMode.NoCheck,
                    }
                };

                return handler;

            });
            builder.Services.AddHttpClient("yn", client =>
            {
                client.BaseAddress = new Uri("https://yunwei.yunnan.gwhome:34443/");
                client.DefaultRequestVersion = new Version(2, 0);
                client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
                client.Timeout = TimeSpan.FromSeconds(10);
            }).ConfigurePrimaryHttpMessageHandler(() =>
            {
                var certs = X509CertificateLoader.LoadPkcs12CollectionFromFile("./certs/李克善.p12", "wXsjm1VN");
                var handler = new SocketsHttpHandler
                {
                    UseCookies = true,
                    AllowAutoRedirect = false,
                    // 设置客户端证书
                    SslOptions = new SslClientAuthenticationOptions
                    {
                        TargetHost = "yunwei.yunnan.gwhome",
                        //ClientCertificates = new X509CertificateCollection { cert },
                        ClientCertificates = certs,
                        // 设置服务器证书验证回调（仅测试用）
                        RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true,
                        // 设置 SSL/TLS 协议版本
                        EnabledSslProtocols = SslProtocols.Tls13,
                        // 设置客户端认证选项
                        CertificateRevocationCheckMode = X509RevocationMode.NoCheck,
                    }
                };

                return handler;

            });
            // 设置 HttpClient 的 BaseAddress 为当前应用的地址

            builder.Services.AddHttpClient("local", client =>
            {
                client.BaseAddress = new Uri("http://localhost:5244/");
            }).ConfigurePrimaryHttpMessageHandler(() =>
            {
                var handler = new HttpClientHandler()
                {
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true, // 仅测试
                };
                return handler;
            });

            builder.Services.AddHttpClient("uid", client =>
            {
                client.BaseAddress = new Uri("http://192.168.240.196:8888/");
            }).ConfigurePrimaryHttpMessageHandler(() =>
            {
                var handler = new HttpClientHandler()
                {
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true, // 仅测试
                };
                return handler;
            });


            //添加重试机制
            builder.Services.AddResiliencePipeline("my-pipeline", builder =>
            {
                builder
                    .AddRetry(new RetryStrategyOptions {
                        //ShouldHandle = new Polly.PredicateBuilder().Handle<Exception>(),
                        BackoffType = DelayBackoffType.Exponential,
                        UseJitter = true,  // Adds a random factor to the delay
                        MaxRetryAttempts = 4,
                        Delay = TimeSpan.FromSeconds(3),
                    })
                    .AddTimeout(TimeSpan.FromSeconds(10));
            });

            #endregion
            var app = builder.Build();


            // 初始化 ABP 应用
            // 初始化ABP应用
            await app.InitializeApplicationAsync();
            // 数据种子
            using (var scope = app.Services.CreateScope())
            {
                var dataSeeder = scope.ServiceProvider.GetRequiredService<IDataSeeder>();
                await dataSeeder.SeedAsync(new DataSeedContext()
                    .WithProperty(IdentityDataSeedContributor.AdminEmailPropertyName, IdentityDataSeedContributor.AdminEmailDefaultValue)
                    .WithProperty(IdentityDataSeedContributor.AdminPasswordPropertyName, IdentityDataSeedContributor.AdminPasswordDefaultValue));
            }

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                //app.UseHsts();
            }

            //app.UseHttpsRedirection();

            app.UseAntiforgery();

            app.MapStaticAssets();
            app.MapRazorComponents<App>()
                .AddInteractiveServerRenderMode();

            app.Run();
        }

        // 新增方法：从 Windows 证书存储区加载证书
        private static X509Certificate2 LoadCertificateFromStore(string subjectOrFriendlyName)
        {
            // 尝试在当前用户的“个人”存储区中查找
            using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
            {
                store.Open(OpenFlags.ReadOnly);
                var collection = store.Certificates.Find(X509FindType.FindBySubjectName, subjectOrFriendlyName, false);
                if (collection.Count > 0)
                {
                    return collection[0]; // 返回第一个匹配的证书
                }
            }

            // 尝试在本地计算机的“个人”存储区中查找
            using (var store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
            {
                store.Open(OpenFlags.ReadOnly);
                var collection = store.Certificates.Find(X509FindType.FindBySubjectName, subjectOrFriendlyName, false);
                if (collection.Count > 0)
                {
                    return collection[0];
                }
            }

            return null;
        }


    }
}
